<template>
  <div class="app-container">

    <!-- 搜索表单 -->
    <el-form ref="queryRef" :inline="true" :model="queryParams" v-show="showSearch" label-width="68px">
      <el-form-item label="品牌名称" prop="name">
        <el-input
            placeholder="请输入品牌名称"
            clearable
            v-model="queryParams.name"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 功能按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['product:brand:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['product:brand:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['product:brand:remove']"
        >删除
        </el-button>
      </el-col>
      <!-- 功能按钮栏 -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" v-hasPermi="['product:brand:list']"></right-toolbar>
    </el-row>

    <!-- 数据展示表格 -->
    <el-table :data="brandList" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="品牌名称" prop="name" width="200"/>
      <el-table-column label="品牌图标" prop="logo" #default="scope">
        <img :src="scope.row.logo" width="50"/>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['product:brand:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['product:brand:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条组件 -->
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 新增或修改分类品牌对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="brandRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌图标" prop="logo">
          <el-upload
              class="avatar-uploader"
              :action="imgUpload.url"
              :headers="imgUpload.headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.logo" :src="form.logo" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="Brand">
//=================1.导入区域=================
import { listBrand,addBrand,getBrandById,updateBrand,deleteById } from '@/api/product/brand'
import { getToken } from '@/utils/auth'
import { ElMessage,ElMessageBox } from 'element-plus'
import {resetForm} from "@/utils/ruoyi.js";



//=================2.变量区域=================
const { proxy } = getCurrentInstance();


//定义分页列表数据模型
const brandList = ref([]);
//定义列表总记录数模型
const total = ref(2);
// 加载数据效果
const loading = ref(false);

const data = reactive({
  queryParams: {
    name: null,
    pageNum: 1,
    pageSize: 10
  },
  form: {
    id: null,
    name: null,
    logo: null,
  },
  imgUpload: {
    //VITE_APP_BASE_API = '/dev-api'
    url: import.meta.env.VITE_APP_BASE_API+'/file/upload',
    headers: {
      Authorization: 'Bearer ' + getToken()
    }
  },
  rules: {
    name: [{ required: true, message: "品牌名称不能为空", trigger: "blur" }],
    logo: [{ required: true, message: "品牌LOGO不能为空", trigger: "blur" }],
  }
})

const {queryParams,form,imgUpload,rules} =  toRefs(data); //将reactive声明的多个参数，转换为单个ref变量

//添加或修改对话框标题
const title = ref('')

//添加或修改对话框是否显示
const open = ref(false)

//批量操作
const ids = ref([])

//删除多个数据的按钮状态
const multiple = ref(true)
//修改按钮状态
const single = ref(true)

//定义隐藏搜索控制模型
const showSearch = ref(true);

//=================3.事件处理区域=================
function getList(){
  loading.value = true
  listBrand(queryParams.value).then((result)=>{
    loading.value = false
    brandList.value = result.rows
    total.value = result.total
  })
}

function handleQuery(){
  getList();
}

/*function resetQuery(){
  queryParams.value.name = null
  queryParams.value.pageNum = 1
  queryParams.value.pageSize = 10
  getList()
}*/
function resetQuery(){
  proxy.resetForm('queryRef')
  getList()
}

getList();

//新增弹出添加表单
function handleAdd(){
  open.value = true
  title.value = '添加'
  reset()
}
/*function reset(){
  form.value.id = null
  form.value.name = null
  form.value.logo = null

  //或
  form.value = {
    id: null,
    name: null,
    logo: null
  };
}*/
function reset(){
  proxy.resetForm('brandRef')
}

function handleAvatarSuccess(result,uploadFile){
  debugger
  form.value.logo = result.data.url
  proxy.$refs['brandRef'].clearValidate('logo')
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片必须是JPG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('图片大小不能超过 1MB!')
    return false
  }
  return true
}

//添加
function submit(){
  proxy.$refs["brandRef"].validate((valid)=>{
    if(valid){ //true表单数据合法

      if(form.value.id){ //  id==null  就是false   进行修改操作
        updateBrand(form.value).then(result=>{
          //ElMessage.success(result.msg)
          proxy.$modal.msgSuccess(result.msg)
          open.value = false
          getList()
        })
      }else{ //进行添加操作
        addBrand(form.value).then(result=>{
          //ElMessage.success(result.msg)
          proxy.$modal.msgSuccess(result.msg)
          open.value = false
          getList()
        })
      }
    }else{ //false表单数据不合法
      proxy.$modal.msgError('表单数据不合法')
    }
  })

}

function cancel(){
  open.value = false
  reset()
}


function handleUpdate(row){
  open.value = true
  title.value = '修改'
  let _id = row.id || ids.value
  getBrandById(_id).then(result=>{
    form.value = result.data
  })
}

//删除
/*function handleDelete(row){
  let _id = row.id || ids.value

  ElMessageBox.confirm('您确定要删除数据吗?','提示',{
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(()=>{ //确认
    deleteById(_id).then(result=>{
      ElMessage.success(result.msg)
      getList()
    })
  }).catch(()=>{ //取消
    ElMessage.info('取消删除')
  })

}*/
function handleDelete(row){
  let _id = row.id || ids.value

  proxy.$modal.confirm('您确定要删除数据吗?').then(()=>{ //确认
    deleteById(_id).then(result=>{
      ElMessage.success(result.msg)
      getList()
    })
  }).catch(()=>{ //取消
    ElMessage.info('取消删除')
  })

}


function handleSelectionChange(selection){ //  selection是一个数组， 被勾选表体数据
  ids.value = selection.map(item=>{
    return item.id
  })

  multiple.value = ids.value.length == 0
  single.value = ids.value.length!=1
}

</script>






<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>